package com.axin.web.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.axin.blog.api.domain.WebUser;
import com.axin.common.core.domain.web.AjaxResult;
import com.axin.web.annotation.CurrentUser;
import com.axin.web.service.WebUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author axin
 * @Date 2021/11/7 10:52
 **/
@RestController
@RequestMapping("/webUser")
public class ApiWebUserController {



    @Autowired
    private WebUserService webUserService;

    /**
     * 用户修改信息
     *
     * @param edit
     * @return
     */
    @PutMapping("/edit")
    public AjaxResult editUserInfo(@Validated @RequestBody WebUser edit, HttpServletRequest request) {

        webUserService.editUserInfo(edit, request);

        return AjaxResult.success();
    }

    @PutMapping("/updatePwd")
    public AjaxResult<Void> updatePwd(@CurrentUser WebUser loginUser,
                                      HttpServletRequest request,
                                      @RequestParam("oldPassword") String oldPassword,
                                      @RequestParam("newPassword") String newPassword) {

        String password = loginUser.getPassword();
        if (!StrUtil.equals(password, SecureUtil.md5(oldPassword))) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (StrUtil.equals(password, SecureUtil.md5(newPassword))) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        webUserService.resetUserPwd(loginUser, SecureUtil.md5(newPassword), request);
        return AjaxResult.success();
    }

}
